<template>
  <div class="main-container">
    <el-form inline :model="searchParams">
      <el-form-item>
        <el-select v-model="searchParams.workerName" placeholder="请选择员工">
          <el-option v-for="item in workerList" :key="item.id" :label="item.userName" :value="item.userName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchParams.taskType" class="w150" placeholder="类型" filterable clearable>
          <template v-for="item in typeList">
            <el-option :label="item" :value="item" :key="item"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchParams.taskState" class="w150" placeholder="状态" filterable clearable>
          <template v-for="item in stateList">
            <el-option :label="item" :value="item" :key="item"></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchParams.taskRemark" class="w150" placeholder="工作内容"></el-input>
      </el-form-item>
      <el-form-item label-width="150">
        <el-date-picker v-model="searchParams.beginDate" type="date" placeholder="开始日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearchParams()">清空</el-button>
        <el-button type="primary" @click="query()">查询</el-button>
        <el-button type="primary" @click="dialogOpen()" v-if="$checkAuth('小时单价维护')">小时单价设置</el-button>
      </el-form-item>
    </el-form>

    <!-- 日工小时单价设置 只有管理员权限可以 -->
    <el-dialog width="400px" title="日工小时单价设置" @close="dialogClose" :visible="showHourPriceDialog">
      <div style="border-top: 1px solid #eee; padding: 10px 0px; background: #fefefe; text-align: center">
        <el-form>
          <template v-for="(dayPrice, index) in dayPriceList">
            <el-form-item :key="index">
              <el-row>
                <el-col :span="16">
                  <el-input-number v-model="dayPriceList[index]" :min="100" :max="500" :step="10" step-strictly></el-input-number>
                </el-col>
                <el-col :span="6">
                  <span>{{ dayPriceList[index] / 8 }}/小时</span>
                </el-col>
                <el-col :span="2">
                  <el-button type="text" @click="hourPriceRemove(index)">删除</el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </template>
        </el-form>
        <el-button type="primary" @click="hourPriceAdd">添加</el-button>
        <el-button type="primary" @click="hourPriceSave">保存</el-button>
        <el-button @click="dialogClose">取消</el-button>
      </div>
    </el-dialog>

    <div class="h-100percent overflow-auto">
      <el-table border :data="recordList" class="w-100percent mb20">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="taskState" label="任务状态" align="center" width="100"></el-table-column>
        <el-table-column prop="taskType" label="任务类型" align="center" width="80"></el-table-column>
        <el-table-column prop="createTime" label="提交时间" align="center" width="150"></el-table-column>
        <el-table-column prop="workerName" label="提交人员" align="center" width="80"></el-table-column>
        <el-table-column prop="taskRemark" label="工作备注" align="center" width="250"></el-table-column>
        <el-table-column prop="workHour" label="实动工时" align="center" width="80"></el-table-column>
        <el-table-column label="工作时间" align="center" width="200">
          <template slot-scope="scope">
            <span class="nbsp">{{ formatTimeList(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" align="center" width="150"></el-table-column>
        <el-table-column prop="reviewerName" label="审核人员" align="center" width="80"></el-table-column>
        <el-table-column prop="reviewRemark" label="审核备注" align="center" width="150"></el-table-column>

        <el-table-column prop="hourPrice" label="小时单价" align="center" width="80"></el-table-column>
        <el-table-column prop="quotaHour" label="定额工时" align="center" width="80"></el-table-column>
        <el-table-column label="操作" fixed="right" align="left" min-width="80">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="reviewQuotaHour(scope.row)"
              v-if="scope.row.taskState == '待审核' && $checkAuth('技术类审核') && ['返修', '工装', '调试'].includes(scope.row.taskType)"
              >审核</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="reviewHourPrice(scope.row)"
              v-if="scope.row.taskState == '待审核' && $checkAuth('日工类审核') && ['日工', '维修'].includes(scope.row.taskType)"
              >审核</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleNoticeSizeChange"
        @current-change="handleNoticeCurrentChange"
        :current-page="searchParams.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="searchParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecord"
        background
        class="mt10"
      >
      </el-pagination>
    </div>
    <!-- 日工/维修 小时单价 审核框 -->
    <el-drawer title="单项任务审核" :visible.sync="showReviewHourPrice">
      <el-form v-model="reviewWorkRecord" label-width="100px">
        <el-form-item label="任务类型">
          <el-radio-group v-model="reviewWorkRecord.taskType">
            <el-radio-button label="日工" :disabled="reviewWorkRecord.taskType != '日工'"></el-radio-button>
            <el-radio-button label="维修" :disabled="reviewWorkRecord.taskType != '维修'"></el-radio-button>
            <el-radio-button label="返修" :disabled="reviewWorkRecord.taskType != '返修'"></el-radio-button>
            <el-radio-button label="工装" :disabled="reviewWorkRecord.taskType != '工装'"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务人员">
          <el-input v-model="reviewWorkRecord.workerName" readonly></el-input>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-input v-model="reviewWorkRecord.createTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="实动工时">
          <el-input v-model="reviewWorkRecord.workHour" readonly></el-input>
        </el-form-item>
        <el-form-item label="" v-for="time in reviewWorkRecord.timeList" :key="time.timeId">
          <span class="nbsp">【 {{ time.workDate }} 】 {{ time.beginTime }} - {{ time.endTime }} ( {{ time.workHour }} )</span>
        </el-form-item>
        <el-form-item label="任务备注">
          <el-input v-model="reviewWorkRecord.taskRemark" readonly></el-input>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-form v-model="submitHourPriceParams" label-width="100px">
        <el-form-item label="审核结论">
          <el-radio-group v-model="submitHourPriceParams.conclustion" size="small" @change="hourPriceConclustionChange">
            <el-radio label="1" border>通过</el-radio>
            <el-radio label="0" border>不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="小时单价">
          <el-select v-model="submitHourPriceParams.hourPrice" clearable :disabled="!submitHourPriceParams.needHourPrice">
            <template v-for="item in hourPriceList">
              <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input type="textarea" autosize v-model="submitHourPriceParams.remark"> </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitHourPrice()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 返修/工装 产品工时 审核框 -->
    <el-drawer title="单项任务审核" :visible.sync="showReviewQuotaHour">
      <el-form v-model="reviewWorkRecord" label-width="100px">
        <el-form-item label="任务类型">
          <el-radio-group v-model="reviewWorkRecord.taskType">
            <el-radio-button label="日工" :disabled="reviewWorkRecord.taskType != '日工'"></el-radio-button>
            <el-radio-button label="维修" :disabled="reviewWorkRecord.taskType != '维修'"></el-radio-button>
            <el-radio-button label="返修" :disabled="reviewWorkRecord.taskType != '返修'"></el-radio-button>
            <el-radio-button label="工装" :disabled="reviewWorkRecord.taskType != '工装'"></el-radio-button>
            <el-radio-button label="调试" :disabled="reviewWorkRecord.taskType != '调试'"></el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务人员">
          <el-input v-model="reviewWorkRecord.workerName" readonly></el-input>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-input v-model="reviewWorkRecord.createTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="实动工时">
          <el-input v-model="reviewWorkRecord.workHour" readonly></el-input>
        </el-form-item>
        <el-form-item label="" v-for="time in reviewWorkRecord.timeList" :key="time.timeId">
          <span class="nbsp">【 {{ time.workDate }} 】 {{ time.beginTime }} - {{ time.endTime }} ( {{ time.workHour }} )</span>
        </el-form-item>
        <el-form-item label="任务备注">
          <el-input v-model="reviewWorkRecord.taskRemark" readonly></el-input>
        </el-form-item>
      </el-form>
      <el-divider></el-divider>
      <el-form v-model="submitQuotaHourParams" label-width="100px">
        <el-form-item label="审核结论">
          <el-radio-group v-model="submitQuotaHourParams.conclustion" size="small" @change="quotaHourConclustionChange">
            <el-radio label="1" border>通过</el-radio>
            <el-radio label="0" border>不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="任务工时">
          <el-input type="number" v-model="submitQuotaHourParams.quotaHour" :disabled="!submitQuotaHourParams.needQuotaHour"></el-input>
        </el-form-item>
        <el-form-item label="审核备注">
          <el-input type="textarea" autosize v-model="submitQuotaHourParams.remark"> </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitQuotaHour()">保存</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { namespace } from 'vuex-class'
import dayjs from 'dayjs'
import Layout from '@/views/_common/Layout.vue'
import AddWork from './AddWork.vue'
import ReviewWork from './reviewWork.vue'
import { reviewHourPrice, reviewQuotaHour, saveDayPrice, getDayPrice } from '@/api/attendance'
import { Message } from 'element-ui'
import { getUserWorkerList } from '@/api/interface1'

const vuexAttendance = namespace('SixAttendance')

@Component({
  components: {
    Layout,
    AddWork,
    ReviewWork
  }
})
export default class Index extends Vue {
  // 工作记录列表
  // 工作记录查询接口
  @vuexAttendance.State recordList: any
  @vuexAttendance.State totalRecord: any
  @vuexAttendance.Action GET_ATTENDANCE_LIST: any

  // 工作记录查询条件
  searchParams: any = {
    individual: false,
    workerName: '',
    taskRemark: '',
    taskType: '',
    taskState: '',
    beginTime: '',
    endDate: '',
    page: 1,
    pageSize: 20
  }
  typeList: any = ['日工', '维修', '返修', '工装', '调试']
  stateList: any = ['待审核', '审核通过', '审核未通过']

  // 审核工作记录
  reviewWorkRecord: any = {}

  // 审核弹框视图控制
  showReviewHourPrice: boolean = false
  showReviewQuotaHour: boolean = false
  reviewHourPrice(row) {
    this.initSubmitHourPriceParams()
    this.initSubmitQuotaHourParams()
    this.showReviewHourPrice = true
    this.showReviewQuotaHour = false
    this.reviewWorkRecord = row
    this.submitHourPriceParams.taskId = row.taskId
  }
  reviewQuotaHour(row) {
    this.initSubmitHourPriceParams()
    this.initSubmitQuotaHourParams()
    this.showReviewHourPrice = false
    this.showReviewQuotaHour = true
    this.reviewWorkRecord = row
    this.submitQuotaHourParams.taskId = row.taskId
  }

  // TODO 小时单价 从后端获取
  hourPriceList: any = [
    {
      label: '20/时=160/天',
      value: 20
    },
    {
      label: '22.5/时=180/天',
      value: 22.5
    }
  ]

  submitQuotaHourParams: any = {}
  submitHourPriceParams: any = {}
  initSubmitQuotaHourParams() {
    this.submitQuotaHourParams = {
      taskId: 0,
      conclustion: -1,
      quotaHour: 0,
      needQuotaHour: false,
      remark: ''
    }
  }
  initSubmitHourPriceParams() {
    this.submitHourPriceParams = {
      taskId: 0,
      conclustion: -1,
      hourPrice: 0,
      needHourPrice: false,
      remark: ''
    }
  }

  /**
   * 日工/维修 小时单价 审核结论改变
   */
  hourPriceConclustionChange(e) {
    console.log(e)
    this.submitHourPriceParams.needHourPrice = e == 1 ? true : false
    if (e == 0) this.submitHourPriceParams.hourPrice = 0
  }

  /**
   * 日工/维修 小时单价 提交审核结果
   */
  async submitHourPrice() {
    // 参数校验
    if (this.submitHourPriceParams.conclustion == -1) {
      Message.warning('请选择审核结论')
      return
    }
    if (this.submitHourPriceParams.conclustion == 1 && this.submitHourPriceParams.hourPrice == 0) {
      Message.warning('请确认小时单价')
      return
    }
    let res = await reviewHourPrice({ ...this.submitHourPriceParams })
    if (res) {
      this.showReviewHourPrice = false
      this.showReviewQuotaHour = false
      this.reviewWorkRecord = {}
      this.GET_ATTENDANCE_LIST(this.searchParams)
    }
  }

  /**
   * 返修/工装 工时 审核结论改变
   */

  quotaHourConclustionChange(e) {
    console.log(e)
    this.submitQuotaHourParams.needQuotaHour = e == 1 ? true : false
    if (e == 0) this.submitQuotaHourParams.quotaHour = 0
  }

  /**
   * 返修/工装 工时 提交审核结果
   */
  async submitQuotaHour() {
    // 参数校验
    if (this.submitQuotaHourParams.conclustion == -1) {
      Message.warning('请选择审核结论')
      return
    }
    if (this.submitQuotaHourParams.conclustion == 1 && this.submitQuotaHourParams.quotaHour == 0) {
      Message.warning('请确认任务工时')
      return
    }
    let res = await reviewQuotaHour({ ...this.submitQuotaHourParams })
    if (res) {
      this.showReviewHourPrice = false
      this.showReviewQuotaHour = false
      this.reviewWorkRecord = {}
      this.GET_ATTENDANCE_LIST(this.searchParams)
    }
  }

  // 小时单价设置弹框视图控制
  showHourPriceDialog: boolean = false
  // 日工价钱数组
  dayPriceList: any = []
  /**
   * 小时单价弹框隐藏
   */
  dialogClose() {
    this.showHourPriceDialog = false
  }
  /**
   * 小时单价弹框显示
   */
  dialogOpen() {
    this.apiGetDayPrice()
    this.showHourPriceDialog = true
  }
  /**
   * 小时单价添加
   */
  hourPriceAdd() {
    this.dayPriceList.push(100)
  }
  /**
   * 小时单价删除
   */
  hourPriceRemove(index) {
    this.dayPriceList.splice(index, 1)
  }
  /**
   * 小时单价保存
   */
  async hourPriceSave() {
    // TODO 小时单价保存接口请求
    let res = await saveDayPrice({ ...this.dayPriceList })
    if (res) {
      this.apiGetDayPrice()
      this.dialogClose()
    }
  }
  async apiGetDayPrice() {
    let res = await getDayPrice({})
    if (res) {
      console.log('apiGetDayPrice')
      console.log(res)
      console.log(res.data)
      if (res.data.length < 3) {
        this.dayPriceList = []
        this.hourPriceList = []
      } else {
        let array = JSON.parse(res.data)
        this.dayPriceList = array
        this.hourPriceList = []
        for (let i = 0; i < array.length; i++) {
          let dayPrice = array[i]
          let hourPrice = dayPrice / 8
          let obj = {
            label: hourPrice + '/时=' + dayPrice + '/天',
            value: hourPrice
          }
          this.hourPriceList.push(obj)
        }
      }
    }
  }

  /**
   * 生命周期钩子函数
   */
  created() {
    this.GET_ATTENDANCE_LIST(this.searchParams)
    this.apiGetDayPrice()
    this.getWorkerList()
  }

  workerList: any = []
  /**
   * 获取工人列表
   */
  async getWorkerList() {
    let res = await getUserWorkerList().catch(err => {
      Message.error(err)
    })
    if (res) {
      this.workerList = res.data
    }
  }

  /**
   * 重置查询条件
   */
  resetSearchParams() {
    this.searchParams = {
      individual: false,
      workerName: '',
      taskRemark: '',
      taskType: '',
      taskState: '',
      beginDate: '',
      endDate: '',
      page: 1,
      pageSize: 20
    }
  }

  /**
   * 格式化显示工作时间列表
   */
  formatTimeList(row) {
    let content = ''
    for (let i = 0; i < row.timeList.length; i++) {
      let time = row.timeList[i]
      content += '[' + time.workDate + '] ' + time.beginTime + '-' + time.endTime + '  '
    }
    return content
  }

  /**
   * 条件查询工作记录
   * 先进行参数校验
   */
  query() {
    if (this.searchParams.beginDate) {
      if (this.searchParams.endDate) {
        this.searchParams.endDate = dayjs(this.searchParams.endDate).format('YYYY-MM-DD')
        this.searchParams.beginDate = dayjs(this.searchParams.beginDate).format('YYYY-MM-DD')
        if (this.searchParams.endDate > this.searchParams.beginDate) {
          this.GET_ATTENDANCE_LIST(this.searchParams)
        } else {
          this.$alert('请输入搜索结束日期大于开始日期', '操作提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      } else {
        this.$alert('请同时输入搜索开始与结束日期后，进行搜索', '操作提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
    } else if (this.searchParams.endDate) {
      if (this.searchParams.beginDate) {
        this.searchParams.endDate = dayjs(this.searchParams.endDate).format('YYYY-MM-DD')
        this.searchParams.beginDate = dayjs(this.searchParams.beginDate).format('YYYY-MM-DD')
        if (this.searchParams.endDate > this.searchParams.beginDate) {
          this.GET_ATTENDANCE_LIST(this.searchParams)
        } else {
          this.$alert('请输入搜索结束日期大于开始日期', '操作提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      } else {
        this.$alert('请同时输入搜索开始与结束日期后，进行搜索', '操作提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
    } else {
      this.GET_ATTENDANCE_LIST(this.searchParams)
    }
  }

  handleNoticeSizeChange(newSize) {
    // 分页功能
    this.searchParams.pageSize = newSize
    this.GET_ATTENDANCE_LIST(this.searchParams)
  }
  handleNoticeCurrentChange(newPage) {
    this.searchParams.page = newPage
    this.GET_ATTENDANCE_LIST(this.searchParams)
  }
}
</script>

<style lang="scss" scoped>
.nbsp {
  white-space: pre-wrap;
}
.clearfix {
  zoom: 1; /*IE6*/
}
.clearfix:after {
  content: '.';
  height: 0;
  clear: both;
  display: block;
  visibility: hidden;
}
.inner-table-head {
  th {
    background-color: #f7f7f7 !important;
  }
}
</style>
